package com.example.mcu_up;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;


import com.example.mcu.serial.Pack;
import com.example.mcu.serial.SerialHandlerService;

import com.example.mcu.serial.SerialSend;

import com.example.mcu_up.util.ConfirmDialog;
import com.example.mcu_up.util.ParseXmlService;


import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;

public class MainActivity extends Activity {
	static File mcufile=null;
	static String name="";
	private Recevie recevie=null;
	
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private  boolean cancelUpdate = false;
   
	Intent service=null;
    private static boolean isupdate=false;
    
    private  static int battery_percent=0;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    
  
    private static boolean isTrue=false;
    
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.main1);
		
	    
		
		// service1=new Intent(MainActivity.this,Mcu_server.class);
		// startService(service1);
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
		 
	     
		recevie=new Recevie();
	    IntentFilter filter_dynamic = new IntentFilter();  
	    filter_dynamic.addAction("cozon.moco"); 
        registerReceiver(recevie, filter_dynamic);
       SerialSend.getInstance().sendStatus(SerialSend.Serial_POWER_PERCENT);
        SerialSend.getInstance().sendStatus(SerialSend.Serial_HARDWAREVERSION);
	
	    
	    
	 }
	
	public static String byteToString(byte[] b) {
		StringBuffer buffer = new StringBuffer(b.length);
		for (int i = 0; i < b.length; i++) {
			String strHex = Integer.toHexString(b[i]).toUpperCase();

			if (strHex.length() > 3) {
				buffer.append(strHex.substring(6) + " ");
			} else if (strHex.length() < 2) {
				buffer.append("0" + strHex + " ");
			} else {
				buffer.append(strHex + " ");
			}
		}
		
		return buffer.toString();
	}
	
	public class Recevie extends BroadcastReceiver{
	
		public void onReceive(Context arg0, Intent arg1) {
			
			 name= arg1.getExtras().getString("Msg");
			 Pack p=(Pack) arg1.getExtras().getSerializable("pack");
			 
			 
			 
			 if(name.equals("S_HARDWARE_VERSION")){
				Toast.makeText(MainActivity.this, byteToString(p.getData())+"1", Toast.LENGTH_LONG).show();
				isupdate=isUpdate(byteToString(p.getData()));
	    	}
			 if(name.equals("M_POWER_PERCENT")){
				battery_percent=Pack.readOne(p.getData());
				Toast.makeText(MainActivity.this,"电池的是量是"+String.valueOf(battery_percent), Toast.LENGTH_LONG).show();
				
				
				
				if(isupdate){
					
					if(battery_percent>=50){
						unregisterReceiver(recevie);
						new ConfirmDialog(MainActivity.this,R.style.notitle,mHashMap).show();
						//new ConfirmDialog(MainActivity.this,R.style.notitle).show();
					}else{
						Toast.makeText(MainActivity.this, "电池的电量低于50%,建议您充满电之后再试。", Toast.LENGTH_LONG).show();
					}
					
				}
			}
		  }
		
	}
	
	private boolean isUpdate(String s)
	{  String path=null;
			// 获取当前软件版本
		  String versionCode = s;
		  if(isOpenNetwork()){
			 path= this.getResources().getString(R.string.url);  
		    }else{
		    	Toast.makeText(MainActivity.this, "您没有联网", Toast.LENGTH_LONG).show();
		    }
	
          //包装成url的对象   
          URL url;
          InputStream inStream = null;
          if(path!=null){
		try {
			
			url = new URL(path);
		    HttpURLConnection conn =  (HttpURLConnection) url.openConnection();   
		    conn.setConnectTimeout(5000);  
		    inStream  =conn.getInputStream();  
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  }
		// 把version.xml放到网络上，然后获取文件信息
		//InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
		// 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析
		ParseXmlService service = new ParseXmlService();
		try
		{
			mHashMap = service.parseXml(inStream);
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		if (null != mHashMap)
		{
			String serviceCode = mHashMap.get("version");
			Log.i("iiii",String.valueOf("versionCode"+versionCode));
			Log.i("iiii",String.valueOf("serviceCode"+serviceCode));
			Log.i("iiii",String.valueOf("trueorfalse"+String.valueOf(versionCode.compareTo(serviceCode)<0)));
			// 版本判断
			if (versionCode.compareTo(serviceCode)<0)
			{
				
				
				return true;
			}
		}
	
		return false;
	}
	
	
    
    
    @Override
    protected void onStart() {
    	service=new Intent(MainActivity.this,SerialHandlerService.class);
		 startService(service);
    	super.onStart();
    }
    
    
    
    @Override
    protected void onStop() {
    	stopService(service);
    	SerialSend.getInstance().close();
    	super.onStop();
    }
    
    
    @Override
    protected void onDestroy() {
    	unregisterReceiver(recevie);
    //	stopService(service1);
    	
    	super.onDestroy();
    }
    private boolean isOpenNetwork() {
		ConnectivityManager connManager = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}

		return false;
	}
}
